package com.appointment.pay.rest.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SortedMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.appointment.pay.core.entity.UserAccount;
import com.appointment.pay.core.entity.WxPayTransactionHistory;
import com.appointment.pay.core.enums.TradeStateEnum;
import com.appointment.pay.core.mapper.UserAccountMapper;
import com.appointment.pay.core.mapper.WxPayTransactionHistoryMapper;
import com.appointment.pay.rest.service.IWxPayTransactionService;
import com.appointment.pay.rest.util.DateUtils;

@Service
public class WxPayTransactionServiceImpl implements IWxPayTransactionService {
    
    private static Logger logger = LoggerFactory.getLogger(WxPayTransactionServiceImpl.class);
    
    @Autowired
    private WxPayTransactionHistoryMapper wxpayTransactionMapper;
    
    @Autowired
    private UserAccountMapper userAccountMapper;
    
    private static final String WX_ORDER_QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void handlePayNotify(SortedMap<Object, Object> parameters) {
        
        String result_code = (String)parameters.get("result_code");//业务结果
        String return_msg = (String)parameters.get("return_msg");//错误原因
        if("SUCCESS".equalsIgnoreCase(result_code)){
            //支付成功
            //1,修改支付订单数据状态
            String out_trade_no = (String)parameters.get("out_trade_no");
            WxPayTransactionHistory tran = wxpayTransactionMapper.queryByOutTradeNo(out_trade_no);
            //处理支付状态
            if(TradeStateEnum.SUCCESS.getCode().equalsIgnoreCase(tran.getTradeState())){
                logger.info("该订单数据库状态已经为成功！");
                //do nothing...
            }else if(TradeStateEnum.NOTPAY.getCode().equalsIgnoreCase(tran.getTradeState())){
                //数据库状态未支付
                WxPayTransactionHistory transaction = new WxPayTransactionHistory();
                transaction.setOutTradeNo(out_trade_no);
                transaction.setTradeState(TradeStateEnum.SUCCESS.getCode());
                transaction.setState(1);
                transaction.setStateName(TradeStateEnum.SUCCESS.getMessage());
                String transaction_id = (String)parameters.get("transaction_id");
                transaction.setTransactionId(transaction_id);
                if(parameters.get("coupon_fee") != null){
                    Integer coupon_fee = (Integer)parameters.get("coupon_fee");
                    transaction.setCouponFee(coupon_fee);
                }
                String time_end = (String)parameters.get("time_end");
                SimpleDateFormat format = new SimpleDateFormat(DateUtils.FORMAT2);
                try {
                    Date timeEnd = format.parse(time_end);
                    transaction.setTimeEnd(timeEnd.getTime());//支付完成时间
                }
                catch (ParseException e) {
                    logger.info("支付完成时间格式错误！");
                }
                Integer cash_fee = (Integer)parameters.get("cash_fee");
                transaction.setCashFee(cash_fee);
                transaction.setCorrectTime(new Date());
                wxpayTransactionMapper.updateByOutTradeNo(transaction);
                //2,给用户个人账户加钱
                updateUserAccount(tran);
                
            }else{
                logger.info("该订单数据库状态为："+tran.getTradeState());
            }
                       
        }else{
            //支付失败
            logger.info("微信支付通知结果显示支付失败，result_code="+result_code+", return_msg="+return_msg);        
        }
    }
    
    /**
     * 给用户账户充值
     * @param tran
     */
    private void updateUserAccount(WxPayTransactionHistory tran){
        Integer userId = tran.getUserId();
        Integer totalFee = tran.getTotalFee();//充值金额，单位为分
        UserAccount userAccount = userAccountMapper.queryByUserId(userId);
        BigDecimal inFee = new BigDecimal(totalFee.intValue());
        if(userAccount != null){
            BigDecimal amount = userAccount.getAmount();
            BigDecimal newAmount = amount.add(inFee);
            userAccount.setAmount(newAmount);
            BigDecimal totalRecharge = userAccount.getTotalRecharge();
            BigDecimal newTotalRecharge = totalRecharge.add(inFee);
            userAccount.setTotalRecharge(newTotalRecharge);
            userAccount.setUpdateTime(new Date());
            userAccountMapper.updateUserAccount(userAccount);
        }else{
            userAccount = new UserAccount();
            userAccount.setUserId(userId);
            userAccount.setAmount(inFee);//账户余额
            userAccount.setTotalRecharge(inFee);//累积充值
            userAccount.setCreateTime(new Date());
            userAccountMapper.insertUserAccount(userAccount);
        }
    }
    
}
